<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Models\News\News;
use App\Models\News\NewsCategory;
use App\Models\News\NewsImgExist;
use App\Http\Requests\Admin\News\Create;
use Style,DB,View;

class NewsController extends Controller
{
    public function index(Request $request){
        $input = arrayFilter($request->only(['keyword','category']));
        $news = News::with('newsWithCategory')->
        where(function($query) use ($input){
            $keyword = (!empty($input['keyword'])) ? $input['keyword'] : '';
            if(strlen($keyword) > 0){
                $query->where('title', 'like', '%' . $keyword . '%');
            }
        })->where(function($query) use ($input){
            $category = (!empty($input['category'])) ? $input['category'] : '';
            if(strlen($category) > 0){
                $query->where('category', $category);
            }
        })->orderBy('updated_at','desc')->paginate(20);

        $newsCategory = NewsCategory::select('id','defectsname')->where('level',1)->get();
        return  Style::view('admin.news.index',compact('news','newsCategory','input'));

    }

    /**
     * 资讯发布
     * @param Request $request
     * @return mixed
     */
    public function create(Request $request){

        //查询有一级类
       $firstClass = NewsCategory::select('id','defectsname')->where('level',0)->get();

        if($firstClass){
            foreach($firstClass as $k => $v){
                //默认值
                $k == 0 ? $defaultClass = $v->id : '';
                //查询二级类
                $secondClass = NewsCategory::select('id','defectsname')->where('level',1)->where('pid',$v->id)->get();
                if($secondClass && count($firstClass)>0){

                    foreach($secondClass as  $secondClassKey => $secondClassValue){
                        $Class[$v->id][$secondClassValue->id]=$secondClassValue->defectsname;
                    }
                }
             }
        }


        $Class = json_encode($Class);

        //标题风格 红，黑，蓝
        $color = ["#2d2d2d"=>"黑","#f0514e"=>"红","#0a58e8"=>"蓝"];
        $strRandom = str_random(40);

        return  Style::view('admin.news.create',compact("category","color",'strRandom','Class','firstClass','defaultClass'));

    }

    public function store(Create $request){

        $request->only(['title','source','publisher','category','style','editorValue','recommend','img_tag','firstClass']);
        $input = $request->only(['title','source','publisher','category','style','editorValue','recommend']);
        $request->flash();

        //查找小类是属于哪个大类
        $input['cid'] = $request->firstClass.";".$request->category;
        $input['readnum'] = 0;
        $input['created_at'] = date("Y-m-d H:i:s");
        $input['updated_at'] = date("Y-m-d H:i:s");

        //保存
       if($newsId = News::insertGetId($input)){

           $request->session()->flash('message', '['.$request->title.']添加成功！');
           //检测图片是否已被使用
           $img_url = NewsImgExist::select('id','img_url','img_state')->where('img_tag',$request->img_tag)->get();
           foreach($img_url as $v){
               //有使用状态更新1
               if(strlen(stristr($request->editorValue,$v->img_url))>0){
                   NewsImgExist::where('id',$v->id)->update(['img_state'=>1,'news_id'=>$newsId]);
               }
           }
           return redirect('admin/news/');

        }else{

           $request->session()->flash('message', '['.$request->title.']添加失败！');
           return redirect('admin/news/create')->withInput();

       }
    }

    /**
     * 资讯修改
     * @param $id
     * @return mixed
     */
    public function edit($id){
        //查询有一级类
        $firstClass = NewsCategory::select('id','defectsname')->where('pid',0)->get();
        if($firstClass){
            foreach($firstClass as $k => $v){
                //查询二级类
                $secondClass = NewsCategory::select('id','defectsname')->where('level',1)->where('pid',$v->id)->get();
                if($secondClass && count($firstClass)>0){

                    foreach($secondClass as  $secondClassKey => $secondClassValue){
                        $Class[$v->id][$secondClassValue->id]=$secondClassValue->defectsname;
                    }
                }
            }
        }

        $Class = json_encode($Class);


        //标题风格 红，黑，蓝
        $color = ["#2d2d2d"=>"黑","#f0514e"=>"红","#0a58e8"=>"蓝"];

        //查询储存图片随机码
        $NewsImgExist = NewsImgExist::select('img_tag')->where('news_id',$id)->where('img_state',1)->first();
        if($NewsImgExist){
            $strRandom = $NewsImgExist->img_tag;
        }else{
            $strRandom = str_random(40);
        }
        $newsInfo = News::where('id',$id)->take(1)->get();
        foreach($newsInfo as $v){
            if(strstr($v->cid,';')){
                $class = explode(';',$v->cid);
            }else if(strstr($v->cid,'2:')){
                $class = explode(':',$v->cid);
            }else{
               break;
            }
            $v->firstClass = $class[0];
            $v->secondClass = $class[1];
        }
        return  Style::view('admin.news.edit',compact("category","color",'strRandom','newsInfo','Class','firstClass'));
    }
    /**
     * 资讯更新
     * @param $id
     * @param Create $request
     * @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
     */
    public function update($id,Create $request){

        $input = $request->only(['id','title','source','publisher','category','style','editorValue','recommend']);
        $request->only(['title','source','publisher','category','style','editorValue','recommend','img_tag','firstClass']);
        $input['updated_at'] = date("Y-m-d H:i:s");
        $input['cid'] = $request->firstClass.";".$request->category;

        if(News::where('id',$request->id)->update($input)){
            //检查ubb里有没有上传图片
            $imgFamt = ['.jpg','.png','.gif','.jpeg','.bmp'];
            foreach($imgFamt as $v){
                if(strlen(stristr($request->editorValue,$v))>0){
                    $haveImg = 1;
                    break;
                }else{
                    $haveImg = 0;
                }
            }
            if($haveImg == 1){
                //检测图片是否已被使用
                $img_url = NewsImgExist::select('id','img_url','img_state')->where('img_tag',$request->img_tag)->get();
                foreach($img_url as $v){
                    //有使用状态更新1
                    if(strlen(stristr($request->editorValue,$v->img_url))>0){
                        NewsImgExist::where('id',$v->id)->update(['img_state'=>1,'news_id'=>$request->id]);
                    }else{
                        $picDir = public_path()."/upload/newsimg/".$v->img_url;
                        if(file_exists($picDir)){
                            @unlink($picDir);
                        }else{
                            //echo "不存在";
                        }
                        NewsImgExist::destroy($v->id);
                    }
                }
            }else{
                //删除该新闻以往上传的所有图片
                $NewsImgExist = NewsImgExist::select('id','img_url','created_at')->where('img_state',1)->where('news_id',$request->id)->get();
                if($NewsImgExist){
                    foreach($NewsImgExist as $v){
                        $picDir = public_path()."/upload/newsimg/".$v->img_url;
                        if(file_exists($picDir)){
                            @unlink($picDir);
                        }else{
                            //echo "不存在";
                        }
                        NewsImgExist::destroy($v->id);
                    }
                }
            }

            $request->session()->flash('message', '['.$request->title.']更新成功！');
            return redirect('admin/news/');
        }else{
            $request->session()->flash('message', '['.$request->title.']更新失败！');
            return redirect('admin/news/');
        }
    }

    /**
     * 资讯删除
     * @param $id
     * @param Request $request
     * @return array
     */
    public function destroy($id,Request $request){

        $result = News::where('id', $id)->delete();

        $img_url = NewsImgExist::select('id','img_url','img_state')->where('news_id',$id)->get();

        foreach($img_url as $v){
           $picDir = public_path()."/upload/newsimg/".$v->img_url;
           if(file_exists($picDir)){
                @unlink($picDir);
           }else{
                //echo "不存在";
           }
           NewsImgExist::destroy($v->id);
        }

        if ($result) {
            $request->session()->flash('message', '['.$request->title.']资讯删除成功！');
            $data = [
                'status' => 0
            ];
        } else {
            $request->session()->flash('message','['.$request->title.']资讯删除失败，请稍后重试！！');
            $data = [
                'status' => 1
            ];
        }
        return $data;
    }

    public function upload(Request $request){

        if ($request->hasFile('upfile')) {
            $file=$request->file('upfile');
            $entension = strtolower($file -> getClientOriginalExtension());
            $mimeTye = $file -> getMimeType();
            $clientName = $file -> getClientOriginalName();//客服端文件名
            $size = $file ->  getSize();//文件大小

            if ($file->isValid()) {

                if (!in_array($entension, array('jpg', 'gif', 'png','jpeg','doc','docx','xlsx','xls','pdf','ppt','pptx','rar', 'zip', 'tar','txt'))){

                    return response()->json(['error' => 304, 'info' => "文件类型只能为jpg、gif、png、doc、xls、pdf、ppt、rar、zip、txt！"]);

                }else {

                    $fileurl = date("Ym") . '/';

                    $filename = time() . strtolower(str_random(5)) . '.' . $entension;

                    $request->file('upfile')->move(public_path() . '/upload/newsimg/' . $fileurl, $filename);

                    $data['news_id'] = 0;
                    $data['img_url'] = $fileurl.$filename;
                    $data['img_state'] =0;
                    $data['img_tag'] =$request->img_tag;
                    $data['created_at'] = date("Y-m-d H:i:s");
                    $data['updated_at'] = date("Y-m-d H:i:s");

                    if(NewsImgExist::create($data)){
                        $return = array(
                            "state" => 'SUCCESS',
                            "url" => asset('upload/newsimg/' . $fileurl . $filename),
                            "title" => $clientName,
                            "original" => $clientName,
                            "type" => $mimeTye,
                            "size" => $size
                        );
                        return response()->json($return);
                    }
                }
            }

        }else{
            return response()->json(['error' => 306, 'info' => "没有选择上传图片文件！"]);
        }
    }

    public function config(){

        $json=preg_replace("/\/\*[\s\S]+?\*\//", "", file_get_contents(app_path()."/Vendor/Ueditor/config.json"));
        //echo $json;exit;
        return response()->json(json_decode($json,true));

    }

    /**
     * 图片清理
     * @return mixed
     */
    public function clearPic(){
        //
       $NewsImgExist = NewsImgExist::select('img_url','created_at')->where('img_state',0)->paginate(20);
        foreach($NewsImgExist as $v){
            $v->img_url = "/upload/newsimg/".$v->img_url;
        }
        return  Style::view('admin.news.clearpic',compact("NewsImgExist"));
    }

    public function toClearPic(Request $request){
        $NewsImgExist = NewsImgExist::select('id','img_url','created_at')->where('img_state',0)->get();
        if($NewsImgExist){
            foreach($NewsImgExist as $v){
                $picDir = public_path()."/upload/newsimg/".$v->img_url;
                if(file_exists($picDir)){
                    @unlink($picDir);
                }else{
                    //echo "不存在";
                }
                NewsImgExist::destroy($v->id);
            }
            $request->session()->flash('message', '删除完毕！');
            $data = [
                'status' => 0
            ];
        }else{
            $request->session()->flash('message', '图片路径好像出问题了！');
            $data = [
                'status' => 1
            ];
        }

        return $data;
    }
}
